package com.yayan.filter;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;

/**
 * @description 编码过滤器，解决中文乱码问题
 * @author 刘超
 * @time 2017/7/12
 */
public class CharacterEncodingFilter implements Filter {

	private String encoding = null;

	public void destroy() {
		encoding = null;
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {

		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;

		if (encoding != null) {
			resp.setContentType("text/html;charset=" + encoding);
			req.setCharacterEncoding(encoding);
		}

		chain.doFilter(new CharacterEncodingRequest(req), response);
	}

	public void init(FilterConfig fConfig) throws ServletException {
		encoding = fConfig.getInitParameter("encode");
	}

	class CharacterEncodingRequest extends HttpServletRequestWrapper {

		private HttpServletRequest request;

		public CharacterEncodingRequest(HttpServletRequest request) {
			super(request);
			this.request = request;
		}

		@Override
		public String getParameter(String name) {
			String value = super.getParameter(name);
			if (value == null) {
				return null;
			}

			String method = request.getMethod();
			if ("get".equalsIgnoreCase(method)) {
				try {
					value = new String(value.getBytes("ISO-8859-1"), request.getCharacterEncoding());
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
			}
			return value;

		}

	}

}
